
package com.shop.cloud.mall.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.mall.common.entity.ConfigLogistics;
import com.shop.cloud.mall.admin.mapper.ConfigLogisticsMapper;
import com.shop.cloud.mall.admin.service.ConfigLogisticsService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 物流账号配置
 *
 * @author
 * @date 2023-04-12 11:30:55
 */
@Service
@AllArgsConstructor
public class ConfigLogisticsServiceImpl extends ServiceImpl<ConfigLogisticsMapper, ConfigLogistics> implements ConfigLogisticsService {

	private final RedisTemplate redisTemplate;

	@Override
	@CacheEvict(value = CacheConstants.MALL_CONFIG_LOGISTICS, key = "'value'")
	public boolean updateById(ConfigLogistics entity) {
		return super.updateById(entity);
	}

	ConfigLogistics getOneCashe(){
		ConfigLogistics configLogistics = null;
		String key = getRedisKey();
		//获取缓存配置
		if(redisTemplate.hasKey(key)) {
			Object obj = redisTemplate.opsForValue().get(key);
			if(obj != null){
				configLogistics = JSONUtil.toBean(String.valueOf(obj), ConfigLogistics.class);
			}
		}
		//无缓存则查数据库
		if(configLogistics == null){
			configLogistics = super.getOne(Wrappers.emptyWrapper());
			if(configLogistics != null){
				//存入缓存
				String data = JSONUtil.toJsonStr(configLogistics);
				redisTemplate.opsForValue().set(key, data);
			}
		}
		return configLogistics;
	}

	@Override
	public ConfigLogistics getOne() {
		ConfigLogistics configLogistics = this.getOneCashe();
		if(configLogistics != null
				&& CommonConstants.NO.equals(configLogistics.getIsSelf())){
			//非自配服务，则取平台的配置
			TenantContextHolder.setTenantId(CommonConstants.SYSTEM_TENANT_ID);
			configLogistics = this.getOneCashe();
		}
		return configLogistics;
	}

	String getRedisKey(){
		return StrUtil.format("{}:{}::{}", TenantContextHolder.getTenantId(), CacheConstants.MALL_CONFIG_LOGISTICS, "value");
	}
}
